<template>
    <view class="content">
        <view class="container text-df">
            <!-- <u-navbar :title="title" left-text="返回" right-text="帮助" ></u-navbar> -->
            <view class="cont">
                <scroll-view style="height: 100%;" :scroll-top="scrollTop" :scroll-y="true" upper-threshold="200" 
                     @scrolltoupper="scrolltoupper" :scroll-with-animation="true">
                    <view v-for="(item, index) in messages" :key="index">
                        <!-- 对方 -->
                        <view class="left" v-if="otherId == item.from">
                            <view class="u-flex u-col-left">
                                <image class="header" v-if="item.avatar" :src="item.avatar"></image>
                                <image class="header" v-if="!item.avatar" :src="IMAGEURL + '/static/icon/avatar.png'"></image>
                                
                                <view class="text-left" v-if="item.type === 'TIMTextElem'">
                                    {{ item.payload.text }}
                                </view>
                                <view class="img-left" v-if="item.type === 'TIMImageElem'">
                                    <image @click="bigImg(item.payload.imageInfoArray[1].imageUrl)" mode="widthFix"
                                        :src="item.payload.imageInfoArray[1].imageUrl"></image>
                                </view>
                                <view class="yuyin-box-left" @click="playVoice(item,index)" v-if="item.type === 'TIMSoundElem'">
                                    <image :src="IMAGEURL + 'static/icon/yuyin.png'" class="yuyin"></image>
                                    <view class="yuyin-text">{{ item.voiceText }}</view>
                                </view>
                            </view>
                        </view>
                        <!-- 自己 -->
                        <view class="right" v-if="selfId != item.to">
                            <view class="u-flex u-col-left">
                                <view class="text-right" v-if="item.type === 'TIMTextElem'">
                                    {{ item.payload.text }}
                                </view>
                                <view class="img-right" v-if="item.type === 'TIMImageElem'">
                                    <image @click="bigImg(item.payload.imageInfoArray[1].imageUrl)" mode="widthFix" 
                                        :src="item.payload.imageInfoArray[1].imageUrl"></image>
                                </view>
                                <view class="yuyin-box-right" @click="playVoice(item,index)" v-if="item.type === 'TIMSoundElem'">
                                    <view class="yuyin-text">{{ item.voiceText }}</view>
                                    <image :src="IMAGEURL + 'static/icon/yuyin.png'" class="yuyin"></image>
                                </view>
                                <image class="header" v-if="item.avatar" :src="item.avatar"></image>
                                <image class="header" v-if="!item.avatar" :src="IMAGEURL + '/static/icon/avatar.png'"></image>
                            </view>
                        </view>
                    </view>
                </scroll-view>
            </view>
            
            <view class="top">
                <view class="u-flex u-padding-20">
                    <input class="inp" type="text" placeholder="输入消息" v-model="content" v-if="xiaoxiFlg" @confirm="$noMultipleClicks(sendTxt)">
                	<view class="inp" style="line-height: 76upx;" @touchstart="startManager" @touchend="endManager" v-if="!xiaoxiFlg">{{xiaoxiTxt}}</view>
                	<view @click="$noMultipleClicks(sendTxt)" v-if="xiaoxiFlg">发送</view>
                </view>
                <view class="u-flex">
                	<view class="u-padding-top-10 u-padding-left-40" style="width: 142rpx;">
                	    <image @tap="chooseImage()" style="height: 102rpx;width: 102rpx;" :src="IMAGEURL + 'static/image/upload.png'"></image>
                	    <view class="photo">图片</view>
                	</view>
                	<view class="u-padding-top-10 u-padding-left-40" style="width: 142rpx;">
                	    <image @tap="xianshi" style="height: 102rpx;width: 102rpx;" :src="IMAGEURL + 'static/image/yuyin.png'"></image>
                	    <view class="photo">语音</view>
                	</view>
                </view>
                <view style="height: constant(safe-area-inset-bottom); height: env(safe-area-inset-bottom);"></view>
            </view>
        </view>
    </view>
</template>

<script>
    import { IMAGEURL } from '@/static/js/common.js';
    import TIM from 'tim-wx-sdk';
    import TIMUploadPlugin from 'tim-upload-plugin';
    import { genTestUserSig } from '@/debug/GenerateTestUserSig.js';

    const recorderManager = wx.getRecorderManager();
    
    const recordOptions = {
        duration: 60000, // 录音的时长，单位 ms，最大值 600000（10 分钟）
        sampleRate: 44100, // 采样率
        numberOfChannels: 1, // 录音通道数
        encodeBitRate: 192000, // 编码码率
        format: 'aac' //音频格式，选择此格式创建的音频消息，可以在即时通信 IM 全平台（Android、iOS、微信小程序和Web）互通
    };
    
    let options = {
        SDKAppID: 1600017866 // 接入时需要将 0 替换为您的云通信应用的 SDKAppID
    };
    let tim = TIM.create(options); // SDK 实例通常用 tim 表示
    tim.setLogLevel(0);
    tim.registerPlugin({
        'tim-upload-plugin': TIMUploadPlugin
    });
    // console.log('tim',tim)
    
    export default {
        data() {
            return {
                IMAGEURL,
                messages: [],//列表
                noClick:true,//连点
                content: '', //聊天内容
                scrollTop: 0,
                old: {
                	scrollTop: 0
                },
                xiaoxiFlg: true,
                xiaoxiTxt:'长按开始录音',
                nextReqMessageID: '',
                isCompleted: true,
                audioSrc: '1',
                selfId: '',//自己id
                otherId: '',//对方id
                fromList: '',//1从我的消息列表进入
                innerAudioContext: null,
            };
        },
        onLoad(option) {
            if (option.otherId) {
                this.otherId = option.otherId
            }
            if (option.fromList) {
                this.fromList = option.fromList
            }
            this.selfId = uni.getStorageSync('userId')
            
            if (!this.fromList) {
                this.imLogin()
            } else {
                uni.showLoading({
                	title: '加载中...'
                });
            }
            setTimeout(() => {
                this.getMessageList()
            }, 5000)
            
            // 监听收到消息
            let onMessageReceived = (e) => {
                console.log('-------e-------',e)
                if (e.data&&e.data[0]&&e.data[0].type === 'TIMSoundElem') {
                    this.$set(e.data[0], 'voiceText', '语音消息')
                }
                this.messages.push(e.data[0])
                setTimeout(() => {
                    var len = this.messages.length;
                    this.scrollTop = 3000 * len;
                    this.$closeLoading()
                },300)
            };
            tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived, this);
            
            // 允许使用麦克风权限
            recorderManager.start(recordOptions);
        },
        onHide() {
            this.audioSrc = 1
            this.innerAudioContext.destroy()
            this.innerAudioContext = null
        },
        onUnload() {
            this.audioSrc = 1
            this.innerAudioContext.destroy()
            this.innerAudioContext = null
        },
        methods: {
            // 调用函数登录 IM
            async imLogin() {
                const userID = this.selfId + ''
                const userSig = genTestUserSig(userID).userSig
                const promise = await tim.login({
                    userID: userID,
                    userSig: userSig
                });
                if (promise.code) return false
                console.log('IM登陆成功imLogin', promise);
                if (promise.data.errorInfo == "success") {
                    this.$setSync('IMLogin', 1)
                }
                
                // tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
                tim.setLogLevel(1); // release级别，SDK 输出关键信息，生产环境时建议使用
                uni.showLoading({
                	title: '加载中...'
                });
                return true
            },
            
            // 拉取历史消息
            getMessageList() {
                let promise = tim.getMessageList({
                    conversationID: `C2C${this.otherId}`,// C2C${userID}（单聊）
                });
                promise.then((imResponse) => {
                    let messageList = imResponse.data.messageList; // 消息列表。
                    console.log('messageList', imResponse)
                    
                    if (messageList && messageList.length > 0) {
                        messageList.forEach(cur => {
                            if (cur.type === 'TIMSoundElem') {
                                this.$set(cur, 'voiceText', '语音消息')
                                // this.$set(cur, 'voiceUrl', encodeURIComponent(cur.payload.url))
                            }
                        })
                    }
                    
                    this.messages = messageList
                    setTimeout(() => {
                        var len = this.messages.length; //遍历的数组的长度
                        this.scrollTop = 3000 * len; // 这里我们的单对话区域最高1000，取了最大值，应该有方法取到精确的
                        this.$closeLoading()
                    },300)
                    this.nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
                    this.isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息isCompleted 为 true 时，nextReqMessageID 为 ""。
                });
            },
            
            // 触顶 获取数据
            scrolltoupper() {
                if (!this.isCompleted) {
                    this.getMessageListMore(this.nextReqMessageID)
                }
            },
            
            // 获取更多数据
            getMessageListMore(nextReqMessageID) {
                let promise = tim.getMessageList({
                    conversationID: `C2C${this.otherId}`,
                    nextReqMessageID: nextReqMessageID
                });
                promise.then((imResponse) => {
                    console.log('getMessageListMore', imResponse)
                    let messageList = imResponse.data.messageList; // 消息列表。
                    let newData = messageList
                    if (newData && newData.length > 0) {
                        newData.forEach(cur => {
                            if (cur.type === 'TIMSoundElem') {
                                this.$set(cur, 'voiceText', '语音消息')
                                // this.$set(cur, 'voiceUrl', encodeURIComponent(cur.payload.url))
                            }
                        })
                    }
                    let oldData = this.messages;
                    this.messages = newData.concat(oldData);
                    
                    this.nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
                    this.isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息isCompleted 为 true 时，nextReqMessageID 为 ""。
                });
            },
            
            playVoice(item,index) {
                let that = this
                console.log('this.audioSrc',this.audioSrc == 1,this.innerAudioContext)
                if (this.audioSrc == 1) {
                    this.innerAudioContext = wx.createInnerAudioContext(item.ID);
                    // this.audioSrc = item.payload.remoteAudioUrl
                    this.audioSrc = item._elements[0].content.remoteAudioUrl
                    this.innerAudioContext.src = this.audioSrc
                    this.innerAudioContext.play()
                    this.innerAudioContext.onPlay((res) => {
                        item.voiceText = '播放中...'
                    });
                    
                    this.innerAudioContext.onEnded((res) => {
                        console.log('音频自然播放结束事件',res);
                        item.voiceText = '语音消息'
                        this.audioSrc = 1
                    });
                } else {
                    if (item.voiceText == '播放中...') {
                        this.innerAudioContext.stop();
                        this.innerAudioContext.onStop((res) => {
                            console.log('音频停止事件',res);
                        });
                        item.voiceText = '语音消息'
                        this.audioSrc = 1
                        this.innerAudioContext.destroy()
                    } else  {
                        this.$toast('当前语音播放结束后，才可以播放')
                    }
                }
                
            },
            
            //显示录音
            xianshi() {
                this.xiaoxiFlg = !this.xiaoxiFlg;
            },
            
            // 开始录音
            startManager() {
                recorderManager.start(recordOptions);
                this.xiaoxiTxt = '放开发送语音'
                console.log('11111')
            },
            
            // 结束并发送录音
            endManager() {
                console.log('222')
                // 2.2 监听录音结束事件，录音结束后，调用 createAudioMessage 创建音频消息实例
                recorderManager.onStop((res) => {
                    console.log('recorder stop', res);
                    uni.showLoading({
                    	title: '发送中...'
                    });
                    // 4. 创建消息实例，接口返回的实例可以上屏
                    let message = tim.createAudioMessage({
                        to: this.otherId,
                        conversationType: 'C2C',
                        payload: {
                            // file: res.tempFilePath,
                            file: res
                        },
                        onProgress: percent => {
                            // console.log('onProgress',percent)
                        }
                    });
                    // 5. 发送消息
                    let promise = tim.sendMessage(message);
                    promise.then((imResponse) => {
                        // 发送成功
                        console.log('发送成功-语音',imResponse);
                        let im = imResponse.data.message
                        if (im&&im.type === 'TIMSoundElem') {
                            this.$set(im, 'voiceText', '语音消息')
                        }
                        this.messages.push(im)
                        setTimeout(() => {
                            var len = this.messages.length; //遍历的数组的长度
                            this.scrollTop = 3000 * len; // 这里我们的单对话区域最高1000，取了最大值，应该有方法取到精确的
                        },200)
                        this.$closeLoading()
                    }).catch((imError) => {
                        // 发送失败
                        console.warn('sendMessage error:', imError);
                    });
                    console.log('333')
                });
                this.xiaoxiTxt = '长按开始录音'
                this.xiaoxiFlg = true
                recorderManager.stop();
            },

            sendTxt() {
                if (!this.content) return
                let message = tim.createTextMessage({
                    to: this.otherId, //消息接收方的 userID、groupID 或 topicID
                    conversationType: 'C2C', //会话类型，取值TIM.TYPES.CONV_C2C（端到端会话） 或 TIM.TYPES.CONV_GROUP（群组会话）
                    payload: {
                        text: this.content
                    }
                });
                this.content = ''
                this.messages.push(message)
                console.log(message);
                // 发送消息
                tim.sendMessage(message);
                console.log('列表',this.messages)
                setTimeout(() => {
                    var len = this.messages.length; //遍历的数组的长度
                    this.scrollTop = 3000 * len; // 这里我们的单对话区域最高1000，取了最大值，应该有方法取到精确的
                },100)
            },

            chooseImage() {
                uni.chooseImage({
                    count: 1,
                    sizeType: ['original', 'compressed'],
                    sourceType: ['album','camera'],
                    success: (res) => {
                        let message = tim.createImageMessage({
                            to: this.otherId,
                            conversationType: 'C2C',
                            payload: {
                                file: res
                            },
                            onProgress: function(event) {
                                console.log('file uploading:', event)
                            }
                        });
                        uni.showLoading({
                        	title: '发送中...'
                        });
                        // 2. 发送消息
                        let promise = tim.sendMessage(message)
                        promise.then((imResponse) => {
                            this.messages.push(message)
                            console.log('message', message);
                            console.log('发送成功', imResponse);
                            setTimeout(() => {
                                var len = this.messages.length; //遍历的数组的长度
                                this.scrollTop = 3000 * len; // 这里我们的单对话区域最高1000，取了最大值，应该有方法取到精确的
                            },200)
                            this.$closeLoading()
                        }).catch((imError) => {
                            // 发送失败
                            console.warn('sendMessage error:', imError);
                        });
                    }
                });
            },

            // 点击图像全屏
            bigImg(url) {
                console.log(111)
                wx.previewImage({
                    urls: [url], //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
                    current: '', // 当前显示图片的http链接，默认是第一个
                })
            },
        }
    };
</script>

<style lang="scss">
    .inp {
        flex: 1;
        width: 100%;
        height: 76upx;
        border-radius: 15rpx;
        background-color: #fff;
        padding: 0 30upx;
        box-sizing: border-box;
        margin-right: 10rpx;
    }
    
    page {
        background-color: #f5f5f5;
    }
    
    .text-left{
        border-radius:0 20rpx 20rpx 20rpx;
        word-break: break-all;
        background-color: #fff;
        padding: 20rpx;
        flex: 1;
        margin-left: 20rpx;
    }
    .img-left{
        border-radius:0 20rpx 20rpx 20rpx;
        word-break: break-all;
        background-color: #fff;
        padding: 20rpx;
        flex: 1;
        margin-left: 20rpx;
    }
    .img-left>image{
        width: 300rpx;
    }
    
    .text-right{
        border-radius:20rpx 0 20rpx 20rpx;
        word-break: break-all;
        background-color: #a9e878;
        padding: 20rpx;
        flex: 1;
        margin-right: 20rpx;
    }
    .img-right{
        border-radius:20rpx 0 20rpx 20rpx;
        word-break: break-all;
        background-color: #a9e878;
        padding: 20rpx;
        flex: 1;
        margin-right: 20rpx;
    }
    .img-right>image{
        width: 300rpx;
    }
    
    
    .yuyin-box-left{
        border-radius:0 20rpx 20rpx 20rpx;
        width: 220rpx;
        text-align: left;
        padding: 20rpx;
        flex: 1;
        margin-left: 20rpx;
        background-color: #fff;
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }
    .yuyin-box-right{
        border-radius:20rpx 0 20rpx 20rpx;
        width: 220rpx;
        text-align: left;
        padding: 20rpx;
        flex: 1;
        margin-right: 20rpx;
        background-color: #fff;
        display: flex;
        justify-content: flex-end;
        align-items: center;
    }
    .yuyin{
        width: 30rpx;
        height: 30rpx;
    }
    .yuyin-text{
        padding: 0 15rpx;
    }
    
    
    
    
    
    
    // .bg-gr {
    //     background-color: #a9e878;
    // }
    
    // .user-img {
    //     width: 94rpx;
    //     height: 94rpx;
    // }
    
    .container {
        display: flex;
        flex-direction: column;
        height: 100vh;
    }
    
    .cont {
        flex: 1;
        background: #f1f3fa;
        overflow: hidden;
    }
    
    .left .header,
    .right .header {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
    }
    
    .left {
        width: 100%;
        justify-content: flex-start;
        padding: 10px 20rpx;
        display: flex;
    }
    
    .right {
        width: 100%;
        justify-content: flex-end;
        padding: 10px 20rpx;
        display: flex;
    }
    
    // .tip {
    //     background-color: #fd442f;
    //     border-radius: 50px;
    //     /* padding: 10rpx; */
    //     font-size: 22rpx;
    //     color: #fff;
    //     width: 40rpx;
    //     height: 40rpx;
    //     text-align: center;
    //     line-height: 40rpx;
    // }
    
    // .send {
    //     width: 56rpx;
    //     height: 56rpx;
    // }
    
    // .message {
    //     background: #f1f3fa;
    //     border-radius: 30rpx;
    //     padding: 26rpx;
    //     margin-right: 20rpx;
    // }
    
    .photo {
        color: #aaaaaa;
        text-align: center;
        padding-top: 10rpx;
    }
    
    .top {
        background-color: #f6f6f6;
    }
    
    .search {
        background-color: #FFFFFF;
        height: 80rpx;
        line-height: 80rpx;
        padding-left: 30rpx;
    }
    
    
</style>